<!--新增功能，上半部分表单-->
<template>
  <el-form
    ref="ruleForm"
    :inline="true"
    :model="formInline"
    :rules="rulesdata"
    :label-width="labelWidthStr"
    class="el-form--inline addheadcontentForm"
  >
    <el-form-item
      v-for="item in dataJsonArr"
      :key="item.index"
      :label="item.title"
      :class="{longer: item.class === 'longer'}"
      :prop="item.key"
    >
    
      <div v-if="item.type === 'input'">
        <el-input v-model="formInline[item.key]" v-bind="item.attr" />
      </div>

      <div v-if="item.type === 'number'">
        <el-input
          v-model="formInline[item.key]"
          v-bind="item.attr"
          type="tel"
          @input="handleInput($event, item.key)"
        />
      </div>

      <div v-if="item.type === 'select'">
        <el-select
          v-model="formInline[item.key]"
          v-bind="item.attr"
          :remote-method="remoteMethod"
          @change="selectChange"
          @focus="focuskey(item.key)"
        >
          <el-option
            v-for="items in item.options"
            :key="items.value"
            :title="items.label"
            :label="items.label"
            :value="items.value"
          />
        </el-select>
      </div>

      <div v-if="item.type === 'time'">
        <el-date-picker
          v-model="formInline[item.key]"
          v-bind="item.attr"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </div>

      <div v-if="item.type === 'radio'">
        <template>
          <el-radio
            v-for="items in item.options"
            :key="items.value"
            v-model="formInline[item.key]"
            :label="items.value"
            v-bind="item.attr"
            @change="radioChange(items.value, item.key)"
            >{{ items.label }}</el-radio
          >
        </template>
      </div>

      <div v-if="item.type === 'pdf'">
        <template>
          <UploadPDF
            :imgsrc="formInline[item.key]"
            :keystr="item.key"
            :pdftitle="pdfname"
            @ReturnImgUrl="ReturnpdfUrl"
          />
        </template>
      </div>

      <div v-if="item.type === 'upload'">
        <template>
          <uploadAll
            :page-type="item.attr"
            :imgsrc="formInline[item.key]"
            :keystr="item.key"
            :title="formInline[item.key + 'name']"
            @ReturnImgUrl="ReturnuploadUrl"
          />
        </template>
      </div>

      <div v-if="item.type === 'imgup'">
        <template>
          <PictureUpload
            :imgsrc="formInline[item.key]"
            :keystr="item.key"
            @ReturnImgUrl="ReturnImgUrl"
          />
        </template>
      </div>

      <div v-if="item.type === 'imgupB'">
        <template>
          <uploadFile
            :imgsrc="formInline[item.key]"
            :keystr="item.key"
            :attr="item.attr"
            @ReturnImgUrl="ReturnImgUrl"
          />
        </template>
      </div>

      <div v-if="item.type === 'cascader'">
        <el-cascader
          v-model="formInline[item.key]"
          :options="item.options"
          v-bind="item.attr"
          :props="item.optionProps"
        />
      </div>
    </el-form-item>
    <div v-if="(ButtonDataJson.Arr || []).length === 0">
      <el-form-item v-if="!buttonOffs" class="searchButtonBox">
        <div class="buttonbox">
          <el-button class="submit" @click="serach(1)">确定</el-button>
          <el-button class="reset" @click="reset(0)">取消</el-button>
        </div>
        <div class="" />
      </el-form-item>
    </div>
    <div v-else>
      <el-form-item
        :class="'searchButton' + ButtonDataJson.position"
        class="searchButtonBox"
      >
        <div class="buttonbox">
          <span v-for="(item, i) in ButtonDataJson.Arr || []" :key="i">
            <el-button
              v-if="item.type == 1"
              v-bind="item.attr"
              class="submit"
              @click="serach(i)"
              >{{ item.name }}</el-button
            >
            <el-button
              v-if="item.type == 0"
              v-bind="item.attr"
              class="reset"
              @click="reset(i)"
              >{{ item.name }}</el-button
            >
          </span>
        </div>
        <div class="" />
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import {formatDate} from '@const/filter.js'
import UploadPDF from '@components/businesscomponents/uploadPDF'
import uploadFile from '@components/businesscomponents/uploadFile'
import PictureUpload from '@components/businesscomponents/pictureUpload'
import uploadAll from '@components/businesscomponents/uploadAll'

import {isObject, cloneDeep} from 'lodash'
export default {
  name: 'Search',
  components: {UploadPDF, PictureUpload, uploadFile, uploadAll},
  props: {
    // 表单展示内容
    data: {
      type: Array,
      default: () => []
    },
    // 表单验证内容
    rules: {
      type: Object,
      default: () => {}
    },
    // 详情内容
    details: {
      type: Object,
      default: () => {}
    },
    // 不想要按钮
    buttonOff: {
      type: Boolean,
      default: () => null
    },
    // 自定义按钮
    ButtonData: {
      type: Object,
      default: () => {}
    },
    // 自定义label-width长度
    labelWidth: {
      type: String,
      default: () => ''
    }
  },

  data() {
    // 判断一下按钮是否有没有传 以防报错
    let ButtonDataJson = {}
    if (!this.ButtonData) {
      ButtonDataJson = {
        arr: []
      }
    } else {
      ButtonDataJson = {
        ...this.ButtonData
      }
    }

    return {
      pdfname: '',
      // 自定义表头长度
      labelWidthStr: this.labelWidth || '140px',
      // 自定义按钮
      ButtonDataJson,
      // 判断是否需要按钮
      buttonOffs: false,
      // 表单验证内容
      rulesdata:[],
      // 内容数据
      dataJsonArr: [],
      // 表单默认字段
      formInline: {
        // ...formInlinebox
      },
      // 刚进入时保存表单空字段 用于重置
      formInlinebox: {},
      // 用于保存select为搜索下拉时使用
      selectkey: ''
    }
  },
  watch: {
    data: {
      immediate: true,
      handler(val) {
        this.datafun(val)
      }
    },

    buttonOff: {
      immediate: true,
      handler(val) {
        this.buttonOffs = val
      }
    },

    details: {
      immediate: true,
      handler(val) {
        this.pdfname = val.pdfname
        this.formInline = val
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },

    rules: {
      immediate: true,
      handler(val) {
        this.rulesdata = val
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    }
  },
  methods: {
    datafun(item) {
      // 获取字段，设置默认为空
      let formInlinebox = {}
      item.forEach(item => {
        // 如果有默认值
        if (item.value) {
          formInlinebox[item.key] = item.value
        } else {
          if (item.type === 'cascader') {
            formInlinebox[item.key] = []
          } else {
            formInlinebox[item.key] = null
          }
        }
      })
      this.formInline = formInlinebox
      this.formInlinebox = formInlinebox
      this.dataJsonArr = item

      if (this.$refs['ruleForm']) {
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
        this.ruleFormResetFields()
      }
    },

    // 调用该方法进行数据清空
    ruleFormResetFields() {
      this.$refs['ruleForm'].resetFields()
    },
    // 用于保存select为搜索下拉时使用
    focuskey(key) {
      this.selectkey = key
      this.$emit('focuskey', this.selectkey)
    },

    // 搜索下拉框返回值
    remoteMethod(query) {
      this.$emit('remoteMethod', query, this.selectkey)
    },

    // 选中下拉框的内容
    selectChange(query) {
      this.$emit('selectChange', query, this.selectkey)
    },

    radioChange(query, key) {
      this.$emit('radioChange', query, key)
    },

    // 保存上传的图片
    ReturnImgUrl(condition, key) {
      this.formInline[key] = condition
      this.$refs['ruleForm'].clearValidate(key)
      this.rulesdata[key] = []
    },

    // 保存上传的PDF
    ReturnpdfUrl(condition, key, pdftitle) {
      // 保存上传文件名
      this.pdfname = pdftitle
      this.formInline.pdfname = pdftitle
      // 保存上传路径
      this.formInline[key] = condition
      this.$refs['ruleForm'].clearValidate(key)
      this.rulesdata[key] = []
    },

    // 上传各种文件
    ReturnuploadUrl(condition, key, title) {
      // 保存上传文件名
      // this.formInline[key + 'name'] = title
      this.$set(this.formInline, key + 'name', title)
      // 保存上传路径
      this.formInline[key] = condition
      this.$refs['ruleForm'].clearValidate(key)
      this.rulesdata[key] = []
    },

    // 只能输入数字的输入框
    handleInput(e, key) {
      this.formInline[key] = e.replace(/[^\d]/g, '')
    },

    // 点击提交
    serach(subscript) {
      let index = null
      let obj = {}
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          index = 1
          // 表单数据
          let formdata = {
            ...this.formInline
          }

          // 时间处理  为了点击提交不需要转换时间
          // 这里做了一个处理 在外层需要添加fieldname字段
          // fieldname为数组 必须两个值['开始时间字段',结束时间字段]

          this.dataJsonArr.forEach(item => {
            // 判断当前处理的时间一定是时间段
            if (item.type === 'time' && item.attr.type === 'daterange') {
              // 判断有没有选时间 且有fieldname字段
              if (formdata[item.key] && item.fieldname) {
                // 开始时间
                let starttime = formatDate(
                  formdata[item.key][0],
                  'YYYY-MM-DD HH:mm:ss'
                )
                formdata[item.fieldname[0]] = formdata[item.key][0]

                // 结束时间
                let endingtime = formatDate(
                  formdata[item.key][1],
                  'YYYY-MM-DD HH:mm:ss'
                )
                formdata[item.fieldname[1]] = formdata[item.key][1]

                // 删除多余的时间数组
                delete formdata[item.key]
              }
            }

            // 处理单个时间
            if (item.type === 'time' && item.attr.type === 'date') {
              // 确定选了时间才处理
              if (formdata[item.key]) {
                // 时间转换
                let starttime = formatDate(
                  formdata[item.key],
                  'YYYY-MM-DD HH:mm:ss'
                )
                let timestamp = Date.parse(new Date(starttime))
                // 替换原来字段内容
                formdata[item.key] = timestamp
              }
            }

            // 多选下拉框 转换提交数据
            if (item.type === 'select' && item.attr.multiple) {
              if (formdata[item.key]) {
                formdata[item.key] = formdata[item.key].join(',')
              }
            }

            // 对多类目处理-只返回一个ID
            if (item.type === 'cascader') {
              if (formdata[item.key]) {
                if (isObject(formdata[item.key])) {
                  let index = formdata[item.key].length
                  formdata[item.key] = formdata[item.key][index - 1] + ''
                }
              }
            }
          })
          obj = formdata
          this.$emit('SubmissionForm', formdata, subscript, this.formInlinebox)
        } else {
          let index = 2
          return false
        }
      })

      if (index === 1) {
        return obj
      } else {
        return false
      }
    },

    // 点击取消
    reset(subscript) {
      this.$refs['ruleForm'].resetFields()
      this.formInline = this.formInlinebox
      this.$emit('cancelForm', this.formInline, subscript)
    }
  }
}
</script>

<style lang="less">
.addheadcontentForm {
  .daterange {
    width: 518px !important;
  }

  textarea {
    height: 100%;
  }

  .longer {
    label {
      width: 467px !important;
    }
  }

  .date {
    width: 212px !important;
  }

  .el-form-item {
    margin-right: 16px;
    margin-bottom: 16px;
  }

  .el-input {
    width: 211px;
  }

  .el-input__inner {
    height: 34px;
    line-height: 34px;
    width: 100%;
  }

  .el-form-item__label {
    padding-right: 10px;
  }

  .searchButtonleft {
    text-align: left !important;
  }

  .searchButtoncenter {
    text-align: center !important;
  }

  .searchButtonright {
    text-align: right !important;
  }

  .searchButtonBox {
    display: block;
    height: 34px;
    text-align: center;
    margin-top: 20px;

    .buttonbox {
      min-width: 200px;

      button {
        width: 74px;
        height: 34px;
        cursor: pointer;
        margin-left: 10px;
      }

      .submit {
        background: rgba(35, 113, 197, 1);
        border: 0;
        color: #fff;
      }

      .reset {
        background: rgba(255, 255, 255, 1);
        border: 1px solid rgba(221, 223, 225, 1);
      }
    }

    .clearboth {
      clear: both;
    }
  }
}
</style>
